import React from 'react';
import { Modal } from 'antd';
import { nextTick } from 'utils/nextTick';




class LocationModal extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      isShow: false
    };
    this.onOK = this.onOK.bind(this);
  }

  componentDidMount(){
    const { queryRealTimeGps, record } = this.props;
    queryRealTimeGps({ deviceNo: record.equipmentNo });
  }

  componentWillReceiveProps(next){
    console.log(next.realTimeGps, this.props.realTimeGps);
    if(typeof next.realTimeGps !== 'undefined' ||
       next.realTimeGps !== this.props.realTimeGps){
      nextTick(() => {
        this.map = new window.BMap.Map('myMap');
        const { longitude, latitude } = next.realTimeGps || {};
        if(longitude && latitude){
          this.setState({ isShow: false });
          const point = new window.BMap.Point(longitude, latitude);
          var geoc = new window.BMap.Geocoder();
          this.map.centerAndZoom(point, 14);
          this.map.enableScrollWheelZoom(true);
          const marker = new window.BMap.Marker(point);  // 创建标注
          this.map.addOverlay(marker);
          geoc.getLocation(point, (res) => {
            if(res && res.address){
              var opts = {
                width : 200,     // 信息窗口宽度
                height: 100,     // 信息窗口高度
                title : "详细位置" , // 信息窗口标题
                enableMessage: true//设置允许信息窗发送短息
              };
              var infoWindow = new window.BMap.InfoWindow(`地址：${res.address}`, opts);  // 创建信息窗口对象 
              marker.addEventListener("click", function(){          
                this.map.openInfoWindow(infoWindow,point); //开启信息窗口
              });
            }
          });
        }else{
          this.setState({ isShow: true });
          const point = new window.BMap.Point(116.404, 39.915);
          this.map.centerAndZoom(point, 9);
          this.map.enableScrollWheelZoom(true);
        }
      });
    }
  }

  


  onOK () {
    const { onOK, form, onCancel, record, getList } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        onOK({ ...values, id: record.id }).then(() => {
          onCancel();
          getList();
        });
      }
    });
  }

  render () {
    const { onCancel, loading } = this.props;
    const { isShow } = this.state;
    const modalOpts = {
      confirmLoading: loading,
      title: <div>设备位置 {isShow && <span style={{marginLeft: 6, fontSize: 12, color: 'red'}}>设备从未上线，暂无设备位置</span>}</div>,
      width: 700,
      visible: true,
      maskClosable: false,
      okText: '确定',
      cancelText: '取消',
      onOk: this.onOK,
      onCancel
    };
    return (
      <Modal {...modalOpts}>
        <div style={{ width: '100%', height: '300px' }} id="myMap" />
      </Modal>
    );
  }
}

export default LocationModal;
